import { useCallback } from 'react'
import { useAIAssistantStore, Attachment } from '@/store/aiAssistantStore'
import { useDragDropStore } from '@/store/dragDropStore'
import { useProjectStore } from '@/store/projectStore'
import { nanoid } from 'nanoid'

// 自定义钩子，简化AI助手状态的访问
export const useAIAssistant = () => {
  // 获取状态
  const {
    conversations,
    currentConversation,
    isLoading,
    isSending,
    error,
    fetchConversations,
    createConversation,
    deleteConversation,
    selectConversation,
    addMessage,
    generateAIResponse,
    addAttachment,
    removeAttachment
  } = useAIAssistantStore()
  
  // 获取当前项目
  const { currentProject } = useProjectStore()
  
  // 获取拖拽内容处理函数
  const { dragItemToAttachment } = useDragDropStore()
  
  // 获取当前项目的对话
  const projectConversations = useCallback(() => {
    if (!currentProject) return []
    
    return conversations
      .filter(c => c.projectId === currentProject.id)
      .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
  }, [conversations, currentProject])
  
  // 创建新对话
  const createNewConversation = useCallback(async (title?: string) => {
    if (!currentProject) return null
    
    const conversationTitle = title || `对话 ${projectConversations().length + 1}`
    return await createConversation(currentProject.id, conversationTitle)
  }, [createConversation, currentProject, projectConversations])
  
  // 发送消息并附加拖入内容
  const sendMessage = useCallback(async (content: string, droppedItems?: any[]) => {
    // 如果没有当前对话，先创建一个
    if (!currentConversation) {
      await createNewConversation()
    }
    
    // 收集拖入内容作为附件
    const attachments: Attachment[] = []
    
    if (droppedItems && droppedItems.length > 0) {
      for (const item of droppedItems) {
        attachments.push({
          id: nanoid(),
          type: item.type,
          name: item.title,
          content: item.details,
          previewText: item.summary
        })
      }
    }
    
    // 添加消息
    await addMessage(content, attachments)
  }, [currentConversation, createNewConversation, addMessage])
  
  // 将拖拽内容作为附件添加
  const addAttachmentFromDragItem = useCallback((dragItem: any) => {
    const attachment = dragItemToAttachment(dragItem)
    addAttachment(attachment)
  }, [dragItemToAttachment, addAttachment])
  
  // 获取最后一条AI消息
  const getLastAIMessage = useCallback(() => {
    if (!currentConversation || currentConversation.messages.length === 0) {
      return null
    }
    
    return [...currentConversation.messages]
      .reverse()
      .find(m => m.sender === 'ai')
  }, [currentConversation])
  
  // 获取最后一条用户消息
  const getLastUserMessage = useCallback(() => {
    if (!currentConversation || currentConversation.messages.length === 0) {
      return null
    }
    
    return [...currentConversation.messages]
      .reverse()
      .find(m => m.sender === 'user')
  }, [currentConversation])
  
  return {
    // 状态
    conversations,
    currentConversation,
    isLoading,
    isSending,
    error,
    
    // 基础操作
    fetchConversations,
    createConversation,
    deleteConversation,
    selectConversation,
    addMessage,
    generateAIResponse,
    addAttachment,
    removeAttachment,
    
    // 高级操作
    projectConversations: projectConversations(),
    createNewConversation,
    sendMessage,
    addAttachmentFromDragItem,
    getLastAIMessage: getLastAIMessage(),
    getLastUserMessage: getLastUserMessage()
  }
} 